package com.example.dps;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import com.downpayment.dps.R;


public class TabRoot extends TabActivity {
	
	TabHost tabHost;
	
	ActionBarHelper actionBarHelper;
	
	DBHelper dBHelper;
	
	WebHelper webHelper;
	
	int startIndex = 0;
	
	
	static int setGoalIndex = 0;
	static int viewSavingsIndex = 1;
	static int addMoneyIndex = 2;
	static int mortgageCalcIndex = 3;
	static int resourcesIndex = 4;
	
	String mortgageCalcID = "MortgageCalc";
	String viewSavingsID = "ViewSavings";
	String setGoalID= "SetGoal";
	String addMoneyID = "AddMoney";
	String resourcesID = "Resources";
	
	String[] indexToLabelArray = new String[5];

	
	String mortgageCalcLabel = "Mortgage Calculators";
	String viewSavingsLabel = "View Savings";
	String setGoalLabel = "Create Your Savings Goal";
	String addMoneyLabel = "Add Money";
	String resourcesLabel = "Facts & Info";
	
	public void onDestroy(){
		super.onDestroy();
		this.dBHelper.close();
	}
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig){
		super.onConfigurationChanged(newConfig);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	
	@Override
	public void onBackPressed() {

		Intent i = new Intent();

		i.setClass(this, MainActivity.class);

		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

		startActivity(i);
		finish();
	}
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = null;
		LayoutInflater inflater = null;
		
		switch (id) {
		case Constants.LOGIN_DIALOG:
			builder = new AlertDialog.Builder(this);
		    // Get the layout inflater
		    inflater = this.getLayoutInflater();

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
		    builder.setView(inflater.inflate(R.layout.login_layout, null))
		    // Add action buttons
		           .setPositiveButton("Login", new DialogInterface.OnClickListener() {
		               @Override
		               public void onClick(DialogInterface dialog, int id) {
		            	   
		            	   EditText usernameText = (EditText)((AlertDialog)dialog).findViewById(R.id.loginUsernameValue);
		            	   EditText passwordText = (EditText)((AlertDialog)dialog).findViewById(R.id.loginPasswordValue);
		            	   CheckBox rememberMeBox = (CheckBox)((AlertDialog)dialog).findViewById(R.id.rememberMeCheckBox);
		            	   
		            	   boolean rememberMe = false;
		            	   if(rememberMeBox != null && rememberMeBox.isChecked()) rememberMe = true;
		            	   
		            	   if(rememberMe){
		            		   
		            	   }
		            	   
		            	   if(usernameText != null && passwordText != null){
		            		   String username = usernameText.getText().toString();
		            		   String password = passwordText.getText().toString();

		            		   
		            		   TabRoot.this.webHelper.login(username,password, rememberMe);
		            	   }
		            	   else{
		            		   Toast.makeText(TabRoot.this, "Please enter your username and password", Toast.LENGTH_LONG).show();
		            	   }
		            	   //dialog.
		            	   
		               }
		           })
		           .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                   TabRoot.this.webHelper.logout();
		               }
		           });   
		    
		    
		    //builder.setInverseBackgroundForced(false);
		    /** set checked if remember me = true **/
		    AlertDialog dialog = (AlertDialog) builder.create();
		    
		    dialog.show();
//		    CheckBox box = (CheckBox)dialog.findViewById(R.id.rememberMeCheckBox);
//		    if(box != null){
//		    	if(this.dBHelper.getBoolean(DBHelper.COLUMN_REMEMBER_ME))
//			    	box.setChecked(true);
//			    else
//			    	box.setChecked(false);
//		    }
		    
		    TableRow forgotPass = (TableRow) dialog.findViewById(R.id.forgotPassword);
		    forgotPass.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					
					Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.downpaymentsaver.com/downpaymentserver/forgotPassword.php"));
					startActivity(myIntent);
					
				}
		    	
		    });

		    return dialog;
		    
		}
		
		return null;
	}
	
	//called after a login thread is executed
	public void onAuthenticate(String username, boolean result){	
		
		if(result == true){
			this.dBHelper.setUsername(username);
			
			this.webHelper.getUserInfo();
			
			
			if(this.dBHelper.getMode() == DBHelper.CREATE_ACCOUNT_MODE)
				this.webHelper.getAccountInfo(false);
			

		}
		else{
			this.webHelper.logout();
		}
		
		Intent intent = getIntent();
		finish();
		startActivity(intent);

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.settings_menu, menu);
	    
	    if(this.webHelper.isLoggedIn()){
	    	menu.findItem(R.id.logout).setVisible(true);
	    	menu.findItem(R.id.login).setVisible(false);
	    }
	    else{
	    	menu.findItem(R.id.logout).setVisible(false);
	    	menu.findItem(R.id.login).setVisible(true);
	    }
	    
	    
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.settings:
	            
	        	/** go to settings activity **/
	        	Intent intent = new Intent(TabRoot.this, SettingsActivity.class);
	        	this.startActivity(intent);
	            return true;
	            
	        case R.id.logout:
	        	/** log out user **/
	        	this.webHelper.logout();
	        	
	    		Intent i = new Intent();

	    		i.setClass(this, MainActivity.class);

	    		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

	    		startActivity(i);
	        	
	            return true;
	            
	        case R.id.login:

	        	showDialog(Constants.LOGIN_DIALOG);
	        	
	        	return true;
	        	
	        	
	        default:

	            return super.onOptionsItemSelected(item);
	            
	          
	            
	    }
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab);
		
		
		
		indexToLabelArray[setGoalIndex] = setGoalLabel;
		indexToLabelArray[viewSavingsIndex] = viewSavingsLabel;
		indexToLabelArray[addMoneyIndex] = addMoneyLabel;
		indexToLabelArray[mortgageCalcIndex] = mortgageCalcLabel;
		indexToLabelArray[resourcesIndex] = resourcesLabel;
		
		
		
		Bundle extras = this.getIntent().getExtras();
		
		boolean confirmTransfer = extras.getBoolean("confirmTransfer");
		boolean editAccount = extras.getBoolean("editAccount");
		String viewResource = extras.getString("viewResource");
		
		Utility.adjustBackground(this);
		
		
		dBHelper = new DBHelper(this);
		
		webHelper = new WebHelper(this);
		
		actionBarHelper = new ActionBarHelper(this);
		actionBarHelper.makeBar();
		
		
		/** TabHost will have Tabs */
		tabHost = getTabHost();//(TabHost)findViewById(android.R.id.tabhost);
		
		//tabHost.setBackgroundColor(R.drawable.content_bk_slice);
		
		
		tabHost.getTabWidget().setBackgroundResource(R.drawable.nav_bk_slice);
		
		setStartTab();
		
		
		/** TabSpec used to create a new tab.
		* By using TabSpec only we can able to setContent to the tab.
		* By using TabSpec setIndicator() we can set name to tab. */
		
		/** tid1 is firstTabSpec Id. Its used to access outside. */
		TabSpec MortgageCalcTabSpec = tabHost.newTabSpec(mortgageCalcID);
		TabSpec viewSavingsTabSpec = tabHost.newTabSpec(viewSavingsID);
		TabSpec setGoalTabSpec = tabHost.newTabSpec(setGoalID);
		TabSpec addMoneyTabSpec = tabHost.newTabSpec(addMoneyID);
		TabSpec resourcesTabSpec = tabHost.newTabSpec(resourcesID);
		
		
		/** TabSpec setIndicator() is used to set name for the tab. */
		/** TabSpec setContent() is used to set content for a particular tab. */
		

		View calcIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
		((TextView) calcIndicator.findViewById(R.id.title)).setText("Calculator");
		((ImageView) calcIndicator.findViewById(R.id.icon)).setImageResource(R.drawable.calc_tab_selector);
		MortgageCalcTabSpec.setIndicator(calcIndicator).setContent(new Intent(this,MortgageCalcActivity.class));
		
		View savingsIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
		((TextView) savingsIndicator.findViewById(R.id.title)).setText("View Savings");
		((ImageView) savingsIndicator.findViewById(R.id.icon)).setImageResource(R.drawable.savings_tab_selector);
		viewSavingsTabSpec.setIndicator(savingsIndicator).setContent(new Intent(this,ViewSavingsActivity.class));
		
		View goalIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
		((TextView) goalIndicator.findViewById(R.id.title)).setText("Set Goal");
		((ImageView) goalIndicator.findViewById(R.id.icon)).setImageResource(R.drawable.goal_tab_selector);
		setGoalTabSpec.setIndicator(goalIndicator).setContent(new Intent(this,SetSavingsGoalActivity.class));
		
		View moneyIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
		
		if(confirmTransfer){
			
			((TextView) moneyIndicator.findViewById(R.id.title)).setText("Add Money");
			((ImageView) moneyIndicator.findViewById(R.id.icon)).setImageResource(R.drawable.money_tab_selector);
			addMoneyTabSpec.setIndicator(moneyIndicator).setContent(new Intent(this,ConfirmTransferActivity.class).putExtras(extras));
		}
		else{
			
			((TextView) moneyIndicator.findViewById(R.id.title)).setText("Add Money");
			((ImageView) moneyIndicator.findViewById(R.id.icon)).setImageResource(R.drawable.money_tab_selector);
			addMoneyTabSpec.setIndicator(moneyIndicator).setContent(new Intent(this,AddMoneyActivity.class));
		}
		
		
		
		View resourcesIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
		((TextView) resourcesIndicator.findViewById(R.id.title)).setText("Facts & Info");
		((ImageView) resourcesIndicator.findViewById(R.id.icon)).setImageResource(R.drawable.resources_tab_selector);
		
		/** pass info to link to view a resource **/
		Intent intent = new Intent(this, ResourcesActivity.class);
		if(viewResource != null){
			intent.putExtra("viewResource", viewResource);
		}
		resourcesTabSpec.setIndicator(resourcesIndicator).setContent(intent);
	
		
		/** Add tabSpec to the TabHost to display. */
		
		tabHost.addTab(setGoalTabSpec);
		tabHost.addTab(viewSavingsTabSpec);
		tabHost.addTab(addMoneyTabSpec);
		tabHost.addTab(MortgageCalcTabSpec);
		tabHost.addTab(resourcesTabSpec);
		

		
		
		tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener(){
			@Override
			  public void onTabChanged(String tabId) {

				actionBarHelper.setCurrentView(TabRoot.this.tabIDToString(tabId));
				
				TabRoot.this.startService();
				
				//TabRoot.this.getTabHost().
				
				
			  }
			});
		
		
		
		//this.addTab("Calculator", R.drawable.nav_calculators_icon, MortgageCalcActivity.class);
		//this.addTab("Set Goal", R.drawable.nav_calculators_icon, SetSavingsGoalActivity.class);
		
		tabHost.setCurrentTab(startIndex);
		actionBarHelper.setCurrentView(indexToLabelArray[startIndex]);
		

	}
	
	public void onResume(){
		super.onResume();
		
	}
	

	
	public void setStartTab(){
		
		
		Intent myIntent = getIntent();
		String startTab = myIntent.getStringExtra("START_TAB");
		
		if(startTab.equals("mortgage_calc")) startIndex = mortgageCalcIndex;
		else if(startTab.equals("view_savings")){
			startIndex = viewSavingsIndex;
			//actionBarHelper.setCurrentView("View Your Savings");
		}
		else if(startTab.equals("set_savings_goal")){
			startIndex = setGoalIndex;
			//actionBarHelper.setCurrentView("Set Your Savings Goal");
		}
		else if(startTab.equals("add_money")) startIndex = addMoneyIndex;
		else if(startTab.equals("resources")) startIndex = resourcesIndex;
		else if(startTab.equals("confirm_transfer")){
			
		}
		
		
		/** set current tab to START_TAB (passed from main menu) **/
	
		
	}
	
	
	
	private void addTab(String label, int drawableId, Class<?> cls) {
		Intent intent = new Intent(this, cls);
		TabHost.TabSpec spec = tabHost.newTabSpec(label);
		View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
		TextView title = (TextView) tabIndicator.findViewById(R.id.title);
		title.setText(label);
		ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
		icon.setImageResource(drawableId);

		spec.setIndicator(tabIndicator);
		spec.setContent(intent);
		tabHost.addTab(spec);
		}
	
	
	
	/**
	 * adds the Header to the tab root
	 */
	public void addHeader(){
		
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		RelativeLayout headerLayout = (RelativeLayout) findViewById(R.id.headerLayout);
		
		headerLayout.removeAllViews();
		
		headerLayout.addView(inflater.inflate(R.layout.header_layout, headerLayout, false));
		
		ImageView picture = (ImageView) headerLayout.findViewById(R.id.headerPicture);
		
		if(dBHelper.getImage() != null){
			picture.setImageDrawable(dBHelper.getImage());
		}
		
	}
	
	
	/**
	 *  Returns the tab label from a given tab ID (string). The string id is what is given to the TabSpec
	 * @param id
	 * @return
	 */
	public String tabIDToString(String id){
		
		if(id.equals(mortgageCalcID)) return mortgageCalcLabel;
		else if(id.equals(viewSavingsID)) return viewSavingsLabel;
		else if(id.equals(setGoalID)) return setGoalLabel;
		else if(id.equals(addMoneyID)) return addMoneyLabel;
		else if(id.equals(resourcesID)) return resourcesLabel;
		else return "";
		
	}
	

	
	/** call start service to start or update it **/
	public void startService(){

		Intent serviceIntent = new Intent(this, AddMoneyService.class);
        startService(serviceIntent);
		
	}

	
	public static String getStartTab(Class activity){

		if(activity.toString().equals(AddMoneyActivity.class)){ 
			return "add_money";
		
		}
		
		return "";
	}
	
	
	public void onGetUserInfo(JSONObject json) {
		// TODO Auto-generated method stub

		try {
			String username = json.getString("username");
			String email = json.getString("email");
			String password = json.getString("password");
			int mode = json.getInt("mode");
			int achConfirmed = json.getInt("achConfirmed");
			
			this.dBHelper.setColumnString(DBHelper.COLUMN_USERNAME, username);
			this.dBHelper.setColumnString(DBHelper.COLUMN_EMAIL, email);
			this.dBHelper.setColumnString(DBHelper.COLUMN_PASSWORD, password);
			
			this.dBHelper.setMode(mode);
			this.dBHelper.setBoolean(DBHelper.COLUMN_ACH_CONFIRMED, achConfirmed);
			
			Intent intent = getIntent();
			finish();
			startActivity(intent);
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	
}